package com.jms.fu.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.jms.fu.common.UIMessage;
import com.jms.fu.exception.DAOException;
import com.jms.fu.form.UserForm;
import com.jms.fu.model.bo.UserBO;

public class RegisterAction extends Action {
	private static Logger logger = Logger.getLogger(LoginAction.class);

	/**
	 * Method execute, called when executing the action
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		UserForm userForm = (UserForm) form;
		UserBO userBO = new UserBO();
		String username = userForm.getUsername();
		String password = userForm.getPassword();
		String name = userForm.getName();
		String email= userForm.getEmail();
		try {
			if(userBO.checkUsername(username)){
				request.setAttribute("ErrorInfo", UIMessage.ACCOUNT_EXISTED);
				PrintWriter out = response.getWriter();
				out.print(UIMessage.ACCOUNT_EXISTED);
				out.close();
				return null;
			}
			userBO.addNewUser(username,password,name,email);
			request.setAttribute("pageInfo", UIMessage.REGISTER_SUCCESSFULLY);
			logger.info("Create Account: "+username);
			PrintWriter out = response.getWriter();
			out.print("success");
			out.close();
			return null;
		} catch (DAOException | IOException e) {
			logger.error(e.getMessage());
			return mapping.findForward("error");	
		}
	
		
	}
}
